import { VAxios } from "./Axios"
import type { AxiosTransform } from "./axiosTransform"
import { ContentTypeEnum } from "../enums"
import { handleAxiosError } from "./axiosError"
import { isEmpty, useCommonMessage } from "@/utils"
import { handleResponseData } from "../hooks/useResponse"
import { tokenInfo } from "@/hooks/authorization"

/**
 * @description: 数据处理，方便区分多种处理方式
 */
const transform: AxiosTransform = {
    /**
     * @description 请求之前处理config
     */
    beforeRequestHook: (config, options) => {
        const { apiUrl, apiUrlPrefix, apiModulePrefix } = options
        if (apiModulePrefix) {
            config.url = `${apiModulePrefix}${config.url}`
        }
        if (apiUrlPrefix) {
            config.url = `${apiUrlPrefix}${config.url}`
        }
        if (apiUrl) {
            config.url = `${apiUrl}${config.url}`
        }
    },

    /**
     * @description: 请求拦截器处理
     */
    requestInterceptors: (config, options) => {
        const withToken = options.withToken
        if (withToken !== false) {
            const token = tokenInfo()
            if (!isEmpty(token.authorizationValue)) {
                config.headers.set(token.authorizationHeader, token.authorizationValue)
            }
        }
    },

    /**
     * @description: 响应错误处理
     */
    responseInterceptorsCatch: error => {
        console.error(error)
        const { message, response } = error
        const _message = useCommonMessage()

        if (message.includes("Network Error")) {
            _message.error("网络异常，请稍后再试！")
        } else if (message.includes("timeout")) {
            _message.error("请求超时，请稍后再试！")
        } else if (response) {
            handleAxiosError(response.status, response.data)
        }

        return Promise.reject(error)
    },

    transformResponseData: (response, options) => {
        const { isTransformResponse, isReturnNativeResponse } = options
        // 是否返回原生响应头 比如：需要获取响应头时使用该属性
        if (isReturnNativeResponse) {
            return response
        }
        // 是否对返回结果进行处理
        if (!isTransformResponse) {
            return response.data
        }
        const { data } = response
        return handleResponseData(data, options)
    }
}

export function createAxios() {
    return new VAxios({
        timeout: 10 * 1000,
        headers: { "Content-Type": ContentTypeEnum.JSON },
        transform,
        requestOptions: {
            apiUrl: import.meta.env.VITE_API_URL,
            apiUrlPrefix: import.meta.env.VITE_API_PREFIX,
            withToken: true,
            ignoreCancelToken: true,
            isReturnNativeResponse: false,
            isTransformResponse: true,
            errorFn: true,
            successFn: false
        }
    })
}

export const http = createAxios()
